/* eslint-disable */
import XLSX from 'xlsx';

function auto_width(ws, data) {
    /*set worksheet max width per col*/
    const colWidth = data.map(row => row.map(val => {
        /*if null/undefined*/
        if (val == null) {
            return { 'wch': 10 };
        }
        /*if chinese*/
        else if (val.toString().charCodeAt(0) > 255) {
            return { 'wch': val.toString().length * 2 };
        } else {
            return { 'wch': val.toString().length };
        }
    }))
    /*start in the first row*/
    let result = colWidth[0];
    for (let i = 1; i < colWidth.length; i++) {
        for (let j = 0; j < colWidth[i].length; j++) {
            if (result[j]['wch'] < colWidth[i][j]['wch']) {
                result[j]['wch'] = colWidth[i][j]['wch'];
            }
        }
    }
    ws['!cols'] = result;
}

function json_to_array(key, jsonData) {
    return jsonData.map((v, index) => key.map(j => {
        if (j == 'IsNew') {
            return v[j] == 1 ? '新增' : '';
        }
        if (j == 'R_INDEX') {
            return (index + 1);
        }
        return v[j]
    }));
}

// fix data,return string
function fixdata(data) {
    let o = ''
    let l = 0
    const w = 10240
    for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)))
    o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)))
    return o
}

// get head from excel file,return array
function get_header_row(sheet) {
    const headers = []
    const range = XLSX.utils.decode_range(sheet['!ref'])
    let C
    const R = range.s.r /* start in the first row */
    for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
        var cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })] /* find the cell in the first row */
        var hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
    }
    return headers
}



export const export_table_to_excel = (id, filename) => {
    const table = document.getElementById(id);
    const wb = XLSX.utils.table_to_book(table);
    XLSX.writeFile(wb, filename);

    /* the second way */
    // const table = document.getElementById(id);
    // const wb = XLSX.utils.book_new();
    // const ws = XLSX.utils.table_to_sheet(table);
    // XLSX.utils.book_append_sheet(wb, ws, filename);
    // XLSX.writeFile(wb, filename);
}

export const export_json_to_excel = ({ data, key, title, filename, autoWidth }) => {
    const wb = XLSX.utils.book_new();
    data.unshift(title);
    const ws = XLSX.utils.json_to_sheet(data, { header: key, skipHeader: true });
    if (autoWidth) {
        const arr = json_to_array(key, data);
        auto_width(ws, arr);
    }
    XLSX.utils.book_append_sheet(wb, ws, filename);
    XLSX.writeFile(wb, filename + '.xlsx');
}

export const export_array_to_excel = ({ key, data, title, filename, autoWidth }) => {

    const wb = XLSX.utils.book_new();
    const arr = json_to_array(key, data);
    arr.unshift(title);
    const ws = XLSX.utils.aoa_to_sheet(arr);
    if (autoWidth) {
        auto_width(ws, arr);
    }
    if (filename.length > 31) {
        filename = filename.substr(0, 30)
    }
    XLSX.utils.book_append_sheet(wb, ws, filename);
    XLSX.writeFile(wb, filename + '.xlsx');
}
export const export_array_to_excel_more = ({ key, data, title, filename, autoWidth }) => {

    if (filename.length > 31) {
        filename = filename.substr(0, 30)
    }
    const wb = XLSX.utils.book_new();
    for (var i = 0; i < data.length; i++) {
        const arr = json_to_array(key, data[i]);
        arr.unshift(title);
        var grouptown = data[i][0].GroupTown ? data[i][0].GroupTown : data[i][0].Town;
        var us = [];
        us.push(grouptown);
        const ws = XLSX.utils.aoa_to_sheet(arr);
        if (autoWidth) {
            auto_width(ws, arr);
        }
        XLSX.utils.book_append_sheet(wb, ws, grouptown);
    }
    XLSX.writeFile(wb, filename + '.xlsx');
}

export const export_org_substandard = ({ key, data, title, filename, autoWidth }) => {
    const wb = XLSX.utils.book_new();
    const arr = json_to_array(key, data);
    arr.unshift(title);
    const ws = XLSX.utils.aoa_to_sheet(arr);
    if (autoWidth) {
        auto_width(ws, arr);
    }
    if (filename.length > 31) {
        filename = filename.substr(0, 30)
    }
    var titleStyle = {									//为某个单元格设置单独样式
        font: {
            sz: 14,
            color: { rgb: "000000" },
            bold: true
        },

    };
    var gradeStyle = {									//为某个单元格设置单独样式
        font: {
            sz: 14,
            color: { rgb: "000000" },
            bold: true
        },
        alignment: { vertical: "center", wrapText: true },
    };

    ws["A1"].s = titleStyle;
    ws["B1"].s = titleStyle;
    ws["C1"].s = titleStyle;
    ws["D1"].s = titleStyle;
    ws["E1"].s = titleStyle;
    ws["F1"].s = titleStyle;
    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        if (item.ItemGrade == 1) {
            debugger
            if (ws["A" + (i + 2)]) {
                ws["A" + (i + 2)].s = gradeStyle;
            }
            if (ws["B" + (i + 2)]) {
                ws["B" + (i + 2)].s = gradeStyle;
            }
            if (ws["C" + (i + 2)]) {
                ws["C" + (i + 2)].s = gradeStyle;
            }
            if (ws["D" + (i + 2)]) {
                ws["D" + (i + 2)].s = gradeStyle;
            }
            if (ws["E" + (i + 2)]) {
                ws["E" + (i + 2)].s = gradeStyle;
            }
            if (ws["F" + (i + 2)]) {
                ws["F" + (i + 2)].s = gradeStyle;
            }


        }
    }
    ws["!cols"] = [
        { wch: 10 },
        { wch: 30 },
        { wch: 10 },
        { wch: 10 },
        { wch: 30 },
        { wch: 20 },

    ];
    XLSX.utils.book_append_sheet(wb, ws, filename);
    XLSX.writeFile(wb, filename + '.xlsx');
}
export const export_org_other = ({ key, data, title, filename, autoWidth }) => {
    const wb = XLSX.utils.book_new();
    const arr = json_to_array(key, data);
    arr.unshift(title);
    const ws = XLSX.utils.aoa_to_sheet(arr);
    if (autoWidth) {
        auto_width(ws, arr);
    }
    if (filename.length > 31) {
        filename = filename.substr(0, 30)
    }
    var titleStyle = {									//为某个单元格设置单独样式
        font: {
            sz: 14,
            color: { rgb: "000000" },
            bold: true
        },

    };
    var gradeStyle = {									//为某个单元格设置单独样式
        font: {
            sz: 14,
            color: { rgb: "000000" },
            bold: true
        },
        alignment: { vertical: "center", wrapText: true },
    };

    ws["A1"].s = titleStyle;
    ws["B1"].s = titleStyle;
    ws["C1"].s = titleStyle;
    ws["D1"].s = titleStyle;
    ws["E1"].s = titleStyle;
    ws["F1"].s = titleStyle; 
    for (var i = 0; i < data.length; i++) {
        var item = data[i];
        if (item.ItemGrade == 1) {
            if (ws["A" + (i + 2)]) {
                ws["A" + (i + 2)].s = gradeStyle;
            }
            if (ws["B" + (i + 2)]) {
                ws["B" + (i + 2)].s = gradeStyle;
            }
            if (ws["C" + (i + 2)]) {
                ws["C" + (i + 2)].s = gradeStyle;
            }
            if (ws["D" + (i + 2)]) {
                ws["D" + (i + 2)].s = gradeStyle;
            }
            if (ws["E" + (i + 2)]) {
                ws["E" + (i + 2)].s = gradeStyle;
            }
            if (ws["F" + (i + 2)]) {
                ws["F" + (i + 2)].s = gradeStyle;
            }

        }
    }

    XLSX.utils.book_append_sheet(wb, ws, filename);
    XLSX.writeFile(wb, filename + '.xlsx');
}
export const read = (data, type) => {
    /* if type == 'base64' must fix data first */
    // const fixedData = fixdata(data)
    // const workbook = XLSX.read(btoa(fixedData), { type: 'base64' })
    const workbook = XLSX.read(data, { type: type });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const header = get_header_row(worksheet);
    const results = XLSX.utils.sheet_to_json(worksheet);
    return { header, results };
}
export const readhastitle = (data, type) => {
    const workbook = XLSX.read(data, { type: type });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const headerrow = get_header_row(worksheet);
    var groupname;
    if (headerrow) {
        groupname = headerrow[0];
    } else {
        groupname = '';
    }
    deleteRow(worksheet, 0);
    const header = get_header_row(worksheet);
    const results = XLSX.utils.sheet_to_json(worksheet);
    return { groupname, header, results };
}

export const readhastitlemore = (data, type) => {
    debugger
    var header = null;
    var results = new Array();
    var resultsmodel = new Array();
    const workbook = XLSX.read(data, { type: type });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const headerrow = get_header_row(worksheet);
    var groupname;
    if (headerrow) {
        groupname = headerrow[0];
    } else {
        groupname = '';
    }
    for (var i = 0; i < workbook.SheetNames.length; i++) {
        const tmpName = workbook.SheetNames[i];
        const worksheettmp = workbook.Sheets[tmpName];
        if (worksheettmp['!ref']) {
            const headerrow = get_header_row(worksheettmp);
            var pdesc;
            if (headerrow) {
                pdesc = headerrow[0];
            } else {
                pdesc = '';
            }

            deleteRow(worksheettmp, 0);
            header = get_header_row(worksheet);
            var resulttmp = XLSX.utils.sheet_to_json(worksheettmp);
            var resulttmpmodel = {
                pSheet: tmpName,
                pDesc: pdesc,
                personList: resulttmp
            }
            results = results.concat(resulttmp);
            resultsmodel = resultsmodel.concat(resulttmpmodel);
        }
    }
    return { groupname, header, results, resultsmodel };
}
export const readmore = (data, type) => {
    var header = null;
    var results = new Array();
    var resultsmodel = new Array();
    const workbook = XLSX.read(data, { type: type });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];

    for (var i = 0; i < workbook.SheetNames.length; i++) {
        const tmpName = workbook.SheetNames[i];
        const worksheettmp = workbook.Sheets[tmpName];
        if (worksheettmp['!ref']) {
            header = get_header_row(worksheet);
            var resulttmp = XLSX.utils.sheet_to_json(worksheettmp);
            var resulttmpmodel = {
                pSheet: tmpName,
                personList: resulttmp
            }
            results = results.concat(resulttmp);
            resultsmodel = resultsmodel.concat(resulttmpmodel);
        }
    }
    return { header, results, resultsmodel };
}
function encodeCell(r, c) {
    return XLSX.utils.encode_cell({ r, c });
}

function deleteRow(ws, index) {
    const range = XLSX.utils.decode_range(ws['!ref']);

    for (let row = index; row < range.e.r; row++) {
        for (let col = range.s.c; col <= range.e.c; col++) {
            ws[encodeCell(row, col)] = ws[encodeCell(row + 1, col)];
        }
    }

    range.e.r--;

    ws['!ref'] = XLSX.utils.encode_range(range.s, range.e);
}

function deleteCol(ws, index) {
    const range = XLSX.utils.decode_range(ws['!ref']);

    for (let col = index; col < range.e.c; col++) {
        for (let row = range.s.r; row <= range.e.r; row++) {
            ws[encodeCell(row, col)] = ws[encodeCell(row, col + 1)];
        }
    }

    range.e.c--;

    ws['!ref'] = XLSX.utils.encode_range(range.s, range.e);
}

export default {
    export_table_to_excel,
    export_array_to_excel,
    export_array_to_excel_more,
    export_json_to_excel,
    read,
    readmore,
    readhastitle,
    readhastitlemore,
    export_org_substandard,
    export_org_other
}
